import React, { useEffect, useState } from "react";
import { Cascader, Col, DatePicker, Form, Row, Select, Spin, Switch, message } from "antd";
import http from "../../utils/request";
import { getUrlParam } from "../../utils/getUrlData";
import { getLabelInValue, } from "../../utils/commonJS";
import dayjs from "dayjs";
import { loadProvincesAPI, optionsListAPI } from "../../api/api";
import EmptyView from "../empty/empty";
const { RangePicker } = DatePicker;
const urlData = getUrlParam("data")
const { SHOW_CHILD } = Cascader;

let timeout;
// let currentValue;


// 初始化数据
// const initFormData = {
//     // 时间 ，从url上拿，拿不到则初始化当前月份.
//     time: [getUrlParam("startTime") || dayjs().format('YYYY-MM'), getUrlParam("endTime") || dayjs().format('YYYY-MM')],
//     city: JSON.parse(getUrlParam('city')) || "",
//     engPlantLabelInValue: getLabelInValue('factoryName', 'factoryCode'),
//     salesStoreNameInCode: getLabelInValue('insuredName', 'insuredCode'),
//     salesBrandLabelInValue: getLabelInValue('insuredBrandName', 'insuredBrand'),
//     dealerLabelInValue: getLabelInValue('insuredGroupName', 'insuredGroup'),
//     comLabelInValue: getLabelInValue('secComName', 'secComCode'),
//     teamLabelInValue: getLabelInValue('salesTeamName', 'salesTeam'),
//     businLabelInValue: getLabelInValue('businManagerName', 'salesName'),
//     useLabelInValue: getLabelInValue('useNatureName', 'useNatureCode'),
//     energyTypeLabelInValue: getLabelInValue('fuelTypeName', 'fuelType'),
//     catTypeLabelInValue: getLabelInValue('seriesName', 'seriesCode'),
//     subsidyFlag: getUrlParam('subsidyFlag') || '1'
// }

const initFormData = {
    time: [
        getUrlParam("startTime") ? dayjs(getUrlParam("startTime")) : dayjs(),
        getUrlParam("endTime") ? dayjs(getUrlParam("endTime")) : dayjs(),
    ],
    engPlantLabelInValue: getLabelInValue('factoryName', 'factoryCode'),
    salesStoreNameInCode: getLabelInValue('insuredName', 'insuredCode'),
    dealerLabelInValue: getLabelInValue('insuredGroupName', 'insuredGroup'),
    comLabelInValue: getLabelInValue('secComName', 'secComCode'),
    salesBrandLabelInValue: getLabelInValue('insuredBrandName', 'insuredBrand'),
    teamLabelInValue: getLabelInValue('salesTeamName', 'salesTeam'),
    businLabelInValue: getLabelInValue('businManagerName', 'salesName'),
    useLabelInValue: getLabelInValue('useNatureName', 'useNatureCode'),
    serviceLabelInValue: getLabelInValue('serviceNatureName', 'serviceNature'),
    energyTypeLabelInValue: getLabelInValue('fuelTypeName', 'fuelType'),
    catTypeLabelInValue: getLabelInValue('seriesName', 'seriesCode'),
    subsidyFlag: getUrlParam("subsidyFlag") ? getUrlParam("subsidyFlag") : "",
}


const ModalContent = ({ form, prentParams }) => {
    // 临时保存业务团队代码
    const [selectedSalesTeamCode, setSelectedSalesTeamCode] = useState([])
    // 临时保存二级机构代码
    const [selectedUnitCode, setSelectedUnitCode] = useState([])



    // 查找搜索
    const fetch = ({ value, callback, setLoading, params }) => {

        if (timeout) {
            clearTimeout(timeout);
            timeout = null;
        }
        // currentValue = value;
        const fake = () => {
            http.post({
                url: optionsListAPI,
                params: {
                    data: urlData,
                    ...params,
                    pageIndex: 1,
                    pageSize: 500
                },
                before: () => {
                    setLoading(true)
                },
                success: res => {
                    let { list = [] } = res?.data;
                    callback(list);
                },
                failure: msg => message.error(msg),
                complete: (res) => {

                    setValue('')
                    setLoading(false)
                },
            })


        };
        timeout = setTimeout(fake, 300);
    };



    // 限制时间范围最多只能选择前后12个月。335天
    const [dates, setDates] = useState(null);
    const [hackValue, setHackValue] = useState(null);
    // 限制时间范围最多只能选择前后12个月。335天。
    const disabledDate = (current) => {

        if (!dates) {
            return false;
        }

        const tooLate = dates[0] && current.diff(dates[0], 'days') > 335; //最大不超过12个月
        const tooEarly = dates[1] && dates[1].diff(current, 'days') > 335;//最大不超过12个月
        // if (current) {
        //     return current && current > moment().endOf('month');
        // }
        const test = current && current > dayjs().endOf('month');//今天之后 的月份不能选。
        return !!tooEarly || !!tooLate || !!test;
    };


    // 每次打开时间框
    const onOpenChange = (open) => {
        console.log(open)
        if (open) {
            setHackValue([null, null]);
            setDates([null, null]);
        } else {
            setHackValue(null);
        }
    };


    // 主机厂列表
    const [factoryList, setFactoryList] = useState([])
    const [loadFact, setLoadFact] = useState(false)
    // 经销店列表
    const [shopList, setShopList] = useState([])
    const [loadShop, setLoadShop] = useState(false)
    // 经销店品牌列表
    const [brandList, setBrandList] = useState([])
    const [loadBrand, setLoadBrand] = useState(false)
    // 经销商集团列表
    const [groupList, setGroupLiset] = useState([]);
    const [loadGrop, setLoadGrop] = useState(false)
    // 城市列表
    const [regionLiset, setRegionLiset] = useState([]);
    const [loadRegion, setLoadRegion] = useState(false)
    // 二级机构列表
    const [unitList, setUnitList] = useState([]);
    const [loadUnit, setLoadUnit] = useState(false);
    // 业务团队列表
    const [teamList, setTeamList] = useState([])
    const [loadTeam, setLoadTeam] = useState(false);
    const [teamDisabled, setTeamDisabled] = useState(true);
    // 二级机构变化来决定是否可以使用业务团队字段
    const onChangeUnit = (valueList) => {
        let tempList = [];
        if (valueList && valueList.length > 0) {
            valueList.forEach(item => {
                tempList.push(item.value);
            })
        }
        setSelectedUnitCode(tempList)
        // 二级机构的变化监听，控制是否禁用业务团队 禁用时还要清空业务清理数据
        if (valueList.length && valueList.length > 0) {
            setTeamDisabled(false);
        } else {
            setTeamDisabled(true);
            form.setFieldValue("teamLabelInValue", []);
        }
    }




    // 业务经理列表    
    const [disabled_busin, setDisabled_busin] = useState(true); //禁用业务经理
    const onChangeTeam = (valueList) => {
        let tempList = [];
        if (valueList && valueList.length > 0) {
            valueList.forEach(item => {
                tempList.push(item.value);
            })
        }
        console.log("选中的业务团队代码", tempList);
        setSelectedSalesTeamCode(tempList)
        // 业务团队的变化监听，控制是否禁用业务经理 禁用时还要清空业务清理数据
        if (valueList.length && valueList.length > 0) {
            setDisabled_busin(false);
        } else {
            setDisabled_busin(true);
            form.setFieldValue("businLabelInValue", []);
        }
    }
    const [loadManager, setLoadManager] = useState(false);
    const [managerList, setManagerList] = useState([])

    // 车型系列列表
    const [carModelLiset, setCarModelLiset] = useState([]);
    const [loadCarModel, setLoadCarModel] = useState(false)
    // 使用性质
    const [natureUseList, setNatureUseList] = useState([]);
    const [loadingNatrueUse, setLoadingNatrueUse] = useState(false);
    // 能源种类
    const [energyTypeList, setEnergyTypeList] = useState([]);
    const [loadEnergyType, setLoadEnergyType] = useState(false)
    // 营运性质
    const [serviceList, setServiceList] = useState([]);
    const [loadingService, setLoadingService] = useState(false);


    const [value, setValue] = useState("");

    // 通用搜索事件|接收setState的回调函数
    const handleSearch = (newValue, setCallBack, setLoading, params) => {
        fetch({ value: newValue, callback: setCallBack, setLoading: setLoading, params: params });
    };

    const handleChange = (newValue) => {
        setValue(newValue);
    };


    const loadScreenData = (codeNo = '00', type = 'left') => {
        if (loadRegion) return;
        http.post({
            url: loadProvincesAPI,
            before: () => setLoadRegion(true),
            params: {
                screenType: "1",
                codeNo: codeNo
            },
            success: res => {
                const { data = [] } = res;
                let list = [];
                if (type === 'left' && codeNo === "00") {
                    data.forEach(item => {
                        list.push({
                            ...item,
                            isLeaf: false
                        })
                    })
                    setRegionLiset(list)
                } else {
                    let list = [...regionLiset];
                    let temp = []
                    list.forEach(item => {
                        if (item.codeId === codeNo) {
                            temp.push({
                                ...item,
                                screenDatas: [...data]
                            })
                        } else {
                            temp.push(item)
                        }
                    })
                    setRegionLiset(temp)
                }
            },
            failure: msg => message.error(msg),
            complete: () => setLoadRegion(false),
        })


    }



    useEffect(() => {
        // 获取能源种类和使用性质下拉项  城市下拉项

        loadScreenData("00")
    }, [])
    // 省市区相关 end

    return (
        <>

            <Form
                form={form}
                initialValues={initFormData}
                labelCol={{
                    span: 6,
                }}
            >
                <Row gutter={24}>
                    <Col span={12}>
                        <Form.Item

                            // initialValue={[
                            //     dayjs(),
                            //     dayjs()
                            // ]}
                            label="统计区间"
                            name={'time'}
                        >

                            <RangePicker
                                allowClear={false}
                                disabledDate={disabledDate}
                                onCalendarChange={(val) => setDates(val)}
                                onOpenChange={onOpenChange}
                                format={'YYYY-MM'}
                                style={{ width: "100%" }}
                                picker="month"

                            />
                        </Form.Item>
                    </Col>

                    <Col span={12}>
                        <Form.Item label="主机厂" name='engPlantLabelInValue'>
                            <Select
                                showSearch
                                mode="multiple"
                                value={value}
                                placeholder={'输入搜索主机厂代码'}
                                loading={loadFact}
                                defaultActiveFirstOption={false}
                                allowClear={true} //支持清除
                                onFocus={() => handleSearch('', setFactoryList, setLoadFact, {
                                    screenType: "1",
                                    factoryName: ""
                                })} //鼠标按下去的时候就搜索
                                filterOption={false}
                                onSearch={(newValue) => handleSearch(newValue, setFactoryList, setLoadFact, {
                                    screenType: "1",
                                    factoryName: newValue
                                })}
                                fieldNames={{
                                    label: 'codeValue',
                                    value: 'codeNo'
                                }}
                                onChange={handleChange}
                                notFoundContent={<EmptyView />}
                                options={factoryList}
                                labelInValue={true}
                            />
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item label="经销商" name='salesStoreNameInCode'>
                            <Select
                                showSearch
                                mode="multiple"
                                allowClear={true} //支持清除
                                loading={loadShop}
                                onFocus={() => handleSearch('', setShopList, setLoadShop, {
                                    screenType: "2",
                                    insuredName: ''
                                })} //鼠标按下去的时候就搜索
                                value={value}
                                placeholder={'输入搜索经销店名称'}
                                defaultActiveFirstOption={false}
                                filterOption={false}
                                onSearch={(newValue) => handleSearch(newValue, setShopList, setLoadShop, {
                                    screenType: "2",
                                    insuredName: newValue
                                })}
                                onChange={handleChange}
                                notFoundContent={<EmptyView />}
                                options={shopList}
                                labelInValue={true}  //获取lable  
                                fieldNames={{
                                    label: 'codeValue',
                                    value: 'codeNo'
                                }}
                            />
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item label="经销商集团" name='dealerLabelInValue'>
                            <Select
                                labelInValue={true}
                                loading={loadGrop}
                                mode="multiple"
                                showSearch
                                value={value}
                                placeholder={'输入搜索经销商集团'}
                                defaultActiveFirstOption={false}
                                allowClear={true} //支持清除
                                onFocus={() => handleSearch('', setGroupLiset, setLoadGrop, {
                                    screenType: "4",
                                    insuredGroupName: '',
                                })} //鼠标按下去的时候就搜索
                                filterOption={false}
                                onSearch={(newValue) => handleSearch(newValue, setGroupLiset, setLoadGrop, {
                                    screenType: "4",
                                    insuredGroupName: newValue,
                                })}
                                fieldNames={{
                                    label: 'codeValue',
                                    value: 'codeNo'
                                }}
                                onChange={handleChange}
                                notFoundContent={<EmptyView />}
                                options={groupList}
                            />
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item label="行政区域" name='city'>
                            <Cascader
                                options={regionLiset}
                                changeOnSelect={true}
                                multiple
                                placeholder="全部城市"
                                fieldNames={{
                                    label: "codeValue",
                                    value: "codeId",
                                    children: "screenDatas"
                                }}
                                notFoundContent={loadRegion ? <Spin /> : <EmptyView />}
                                loading={loadRegion}
                                maxTagCount="responsive"
                                mode="multiple"
                                style={{ width: "100%", fontSize: "12px" }}
                                dropdownMenuColumnStyle={{ fontSize: "12px" }}
                                showSearch={false}
                                showCheckedStrategy={SHOW_CHILD}
                                expandTrigger={"hover"}
                                loadData={(options, val) => {
                                    const [object = {}] = options
                                    const { codeId = "" } = object
                                    loadScreenData(codeId, 'right')
                                }}

                            />
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item label="二级机构" name='comLabelInValue'>
                            <Select
                                labelInValue={true}
                                loading={loadUnit}
                                mode="multiple"
                                showSearch
                                value={value}
                                placeholder={'输入搜索二级机构'}
                                defaultActiveFirstOption={false}
                                allowClear={true} //支持清除
                                onFocus={() => handleSearch('', setUnitList, setLoadUnit, {
                                    screenType: "7",
                                    secComName: "",
                                })} //鼠标按下去的时候就搜索
                                filterOption={false}
                                onSearch={(newValue) => handleSearch(newValue, setUnitList, setLoadUnit, {
                                    screenType: "7",
                                    secComName: newValue
                                })}
                                onChange={onChangeUnit}
                                notFoundContent={loadUnit ? <Spin /> : <EmptyView />}
                                options={unitList}
                                fieldNames={{
                                    label: 'codeValue',
                                    value: 'codeNo'
                                }}
                            />
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item label="团队部门" name='teamLabelInValue' >
                            <Select
                                disabled={teamDisabled}
                                labelInValue={true}
                                loading={loadTeam}
                                mode="multiple"
                                showSearch
                                value={value}
                                placeholder={'先选择二级机构后可选择业务团队'}
                                defaultActiveFirstOption={false}
                                allowClear={true} //支持清除
                                onFocus={() => handleSearch('', setTeamList, setLoadTeam, {
                                    screenType: "8",
                                    salesTeamName: "",
                                    secComCode: selectedUnitCode
                                })} //鼠标按下去的时候就搜索
                                filterOption={false}
                                onSearch={(newValue) => handleSearch(newValue, setTeamList, setLoadTeam, {
                                    screenType: "8",
                                    salesTeamName: newValue,
                                    secComCode: selectedUnitCode
                                })}
                                onChange={onChangeTeam}
                                notFoundContent={loadTeam ? <Spin /> : <EmptyView />}
                                options={teamList}
                                fieldNames={{
                                    label: 'codeValue',
                                    value: 'codeNo'
                                }}
                            />
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item label="业务经理" name='businLabelInValue' >
                            <Select
                                disabled={disabled_busin}
                                labelInValue={true}
                                notFoundContent={loadManager ? <Spin /> : <EmptyView />}
                                loading={loadManager}
                                mode="multiple"
                                showSearch
                                value={value}
                                placeholder={'先选择二级业务团队后可选择业务经理'}
                                defaultActiveFirstOption={false}
                                allowClear={true} //支持清除
                                onFocus={() => handleSearch('', setManagerList, setLoadManager, {
                                    screenType: "9",
                                    salesNames: "",
                                    salesTeamCode: selectedSalesTeamCode
                                })} //鼠标按下去的时候就搜索
                                filterOption={false}
                                onSearch={(newValue) => handleSearch(newValue, setManagerList, setLoadManager, {
                                    screenType: "9",
                                    salesNames: newValue,
                                    salesTeamCode: selectedSalesTeamCode
                                })}
                                onChange={handleChange}
                                options={managerList}
                                fieldNames={{
                                    label: 'codeValue',
                                    value: 'codeNo'
                                }}
                            />
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item label="使用性质" name='useLabelInValue'>
                            <Select
                                // 查询参数：useNatureName
                                mode="multiple"
                                defaultActiveFirstOption={false}
                                allowClear={true} //支持清除
                                notFoundContent={loadingNatrueUse ? <Spin /> : <EmptyView />}
                                options={natureUseList}
                                labelInValue={true}
                                loading={loadingNatrueUse}
                                showSearch
                                value={value}
                                placeholder={'选择使用性质'}

                                onFocus={() => handleSearch('', setNatureUseList, setLoadingNatrueUse, {
                                    screenType: "10",
                                    useNatureName: ""
                                })} //鼠标按下去的时候就搜索
                                filterOption={false}
                                onSearch={(newValue) => handleSearch(newValue, setNatureUseList, setLoadingNatrueUse, {
                                    screenType: "10",
                                    useNatureName: newValue
                                })}
                                onChange={handleChange}
                                fieldNames={{
                                    label: 'codeValue',
                                    value: 'codeNo'
                                }}
                            />
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item label="营运性质" name='serviceLabelInValue'>
                            <Select
                                placeholder="选择营运性质"
                                mode="multiple"
                                defaultActiveFirstOption={false}
                                allowClear={true} //支持清除
                                notFoundContent={loadingService ? <Spin /> : <EmptyView />}
                                options={serviceList}
                                labelInValue={true}
                                loading={loadingService}
                                showSearch
                                value={value}
                                onFocus={() => handleSearch('', setServiceList, setLoadingService, {
                                    screenType: "11",
                                    useNatureName: ""
                                })} //鼠标按下去的时候就搜索
                                filterOption={false}
                                onSearch={(newValue) => handleSearch(newValue, setServiceList, setLoadingService, {
                                    screenType: "11",
                                    useNatureName: newValue
                                })}
                                onChange={handleChange}
                                fieldNames={{
                                    label: 'codeValue',
                                    value: 'codeNo'
                                }}
                            />
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item label="能源种类" name='energyTypeLabelInValue'>
                            <Select
                                labelInValue={true}
                                loading={loadEnergyType}
                                mode="multiple"
                                showSearch
                                value={value}
                                placeholder={'输入搜索能源种类'}
                                defaultActiveFirstOption={false}
                                allowClear={true} //支持清除
                                onFocus={() => handleSearch('', setEnergyTypeList, setLoadEnergyType, {
                                    screenType: "12",
                                    fuelTypeName: ""
                                })} //鼠标按下去的时候就搜索
                                filterOption={false}
                                onSearch={(newValue) => handleSearch(newValue, setEnergyTypeList, setLoadEnergyType, {
                                    screenType: "12",
                                    fuelTypeName: newValue
                                })}
                                onChange={handleChange}
                                notFoundContent={loadEnergyType ? <Spin /> : <EmptyView />}
                                options={energyTypeList}
                                fieldNames={{
                                    label: 'codeValue',
                                    value: 'codeNo'
                                }}
                            />
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item label="车型系列" name='catTypeLabelInValue'>
                            <Select
                                loading={loadCarModel}
                                mode="multiple"
                                showSearch
                                value={value}
                                placeholder={'输入搜索车型系列'}
                                defaultActiveFirstOption={false}
                                allowClear={true} //支持清除
                                labelInValue={true}
                                onFocus={() => handleSearch('', setCarModelLiset, setLoadCarModel, {
                                    screenType: "13",
                                    seriesName: '',
                                })} //鼠标按下去的时候就搜索
                                filterOption={false}
                                onSearch={(newValue) => handleSearch(newValue, setCarModelLiset, setLoadCarModel, {
                                    screenType: "13",
                                    seriesName: newValue,
                                })}
                                onChange={handleChange}
                                notFoundContent={loadCarModel ? <Spin /> : <EmptyView />}
                                options={carModelLiset}
                                fieldNames={{
                                    label: 'codeValue',
                                    value: 'codeNo'
                                }}
                            />
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item label="补贴业务" name={'subsidyFlag'} >
                            <Select
                               placeholder="选择补贴业务"
                                allowClear={true}
                                options={[
                                    {
                                        label: "是",
                                        value: '1'
                                    },
                                    {
                                        label: "否",
                                        value: '0'
                                    }
                                ]}>

                            </Select>
                        </Form.Item>
                    </Col>
                    {/* <Col span={12}>
                        <Form.Item label="是否众诚覆盖范围" name={'uticService'} valuePropName="checked">
                            <Select options={[
                                {
                                    label: "是",
                                    value: '1'
                                },
                                {
                                    label: "否",
                                    value: '0'
                                }
                            ]}>

                            </Select>
                        </Form.Item>

                    </Col> */}
                </Row>
            </Form >


        </>
    )

}

export default ModalContent;